import fs from 'fs'
import cheerio from 'cheerio'
import { Analyzer } from './crawler'
export class CourseAnalyzer implements Analyzer {
  // 单例模式
  private static instance: CourseAnalyzer
  static getInstance() {
    if (!CourseAnalyzer.instance) CourseAnalyzer.instance = new CourseAnalyzer()
    return CourseAnalyzer.instance
  }
  private static getCourseInfo(rawHtml: string) {
    const $ = cheerio.load(rawHtml)
    const courseItems = $('.course-item')
    let courseInfo: responseResult.CourseItem[] = []
    courseItems.each(function (i, ele) {
      const descs = $(ele).find('.course-desc')
      const title = descs.eq(0).text()
      const count = parseInt(descs.eq(1).text().split('：')[1])
      courseInfo.push({
        title,
        count
      })
    })
    return courseInfo
  }
  private static generateJsonContent(
    courseInfo: responseResult.CourseItem[],
    filePath: string
  ) {
    let fileContent: responseResult.DataStructure = {}
    if (fs.existsSync(filePath)) {
      fileContent = JSON.parse(fs.readFileSync(filePath, 'utf-8'))
    }
    fileContent[new Date().getTime()] = courseInfo
    return fileContent
  }
  public analyze(rawHtml: string, filePath: string) {
    const courseInfo = CourseAnalyzer.getCourseInfo(rawHtml)
    const fileContent = CourseAnalyzer.generateJsonContent(courseInfo, filePath)
    return JSON.stringify(fileContent)
  }
  private constructor() {}
}
